//
//  SystemExtension.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/9/5.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import Foundation

extension System {
    
    func handleGeTuiClientId(_ id: String) {
        YYAppConfig.set(key: appConfig_notification_clientId, value: id)
        
        uploadGeTuiClientId(id)
    }
    
    func uploadGeTuiClientId(_ id:  String) {
        let params = ["token": YYAppConfig.getOne(key: appConfig_user_token) ?? "", "pushId": id, "deviceId": UIDevice.current.identifierForVendor!.uuidString, "appType": "IOS"]
        yy_get(url: apiUrlPrex + "/md5", parameters: params, success: { (data) in
            yy_Log("handleGeTuiClientId success")
        }) { (errmsg) in
            yy_Log("handleGeTuiClientId error: " + errmsg)
            return nil
        }
    }
    
    func dealGeTuiPayloadData(_ payloadData: Data, offLine: Bool) {
        if let payloadDic = (try? JSONSerialization.jsonObject(with: payloadData, options: .allowFragments)) as? [String: Any] {
            dealGeTuiPayloadDic(payloadDic, offLine: offLine)
        }
    }
    
    func dealGeTuiPayloadDic(_ payloadDic: [String: Any], offLine: Bool) {
        if let topic = payloadDic["topic"] as? String {
            if let url = payloadDic["url"] as? String {
                if offLine {
                    dealGoTo(url: url)
                } else {
                    UIAlertController.yy_showAlert(title: topic, message: payloadDic["messageDes"] as? String, confirmTitle: "前往", confirmAction: {
                        self.dealGoTo(url: url)
                    })
                }
            } else {
                UIAlertController.yy_showAlert(title: topic, message: payloadDic["messageDes"] as? String, confirmTitle: "了解")
            }
        }
    }
    
    func dealGoTo(url: String) {
        var url = url
        if !url.contains("http") {
            url = webviewUrlPrex + url
        }
        
        if let params = YYAlamofire.getUrlParams(url: url) {            
            if YYRouter.currentVC == nil {
                
            } else {
                YYRouter.pushToVC(of: URL(string: url)!.path, params: params)
            }
        }
    }
    
}
